package com.avfh.netcard.common;

import com.avfh.netcard.util.ResponseUtils;
import com.baomidou.mybatisplus.plugins.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseController {

    protected void renderJson(HttpServletResponse response) {
        renderJson(response, new Result<>());
    }

    protected void renderJson(HttpServletResponse response, Page page) {
        if (page.getRecords().isEmpty()) {
            renderJson(response, Result.NULL_RESULT);
            return;
        }

        Result result = new Result<>()
                    .setData(new ResultPage(page));
        renderJson(response, result);
    }

    protected void renderJson(HttpServletResponse response, Object data) {
        if (data == null) {
            renderJson(response, Result.NULL_RESULT);
            return;
        }

        Result result = new Result<>()
                .setData(data);
        renderJson(response, result);
    }

    protected void renderJson(HttpServletResponse response, String code, String msg) {
        Result result = new Result<>()
                .setCode(code)
                .setMsg(msg);
        renderJson(response, result);
    }

    protected void renderJson(HttpServletResponse response, Object data, String code, String msg) {
        Result result = new Result<>()
                .setData(data)
                .setCode(code)
                .setMsg(msg);
        renderJson(response, result);
    }

    protected void renderJson(HttpServletResponse response, Result result) {
        ResponseUtils.renderJson(response, result);
    }

    protected void renderString(HttpServletResponse response, String result) {
        ResponseUtils.renderString(response, result);
    }

    protected <T> Page<T> getPage(HttpServletRequest request){
        Page<T> page = new Page<>();
        String current = request.getParameter("page");
        if (current != null) {
            page.setCurrent(Integer.parseInt(current));
        }
        return page;
    }

    protected Long getUerId(HttpServletRequest request) {
        return (Long) request.getAttribute("userId");
    }

}
